const path = require('path');
const isDev = process.env.NODE_ENV === "development";
const {
    publicPath,
    assetsDir,
    outputDir,
    lintOnSave,
    transpileDependencies,
    title,
    devPort,
    build7z
} = require('./src/config/proj');
const { version, author } = require("./package.json");
const dayJs = require('dayjs');
const date = dayJs().format("YYYY_MM_DD");
const time = dayJs().format("YYYY-MM-DDTHH:mm:ssZ[Z]");
const FileManagerPlugin = require("filemanager-webpack-plugin");
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
const Webpack = require('webpack')
process.env.VUE_APP_TITLE = title || "danduola-template";
process.env.VUE_APP_AUTHOR = author || "danduola@2019";
process.env.VUE_APP_UPDATE_TIME = time;
process.env.VUE_APP_VERSION = version;

const resolve = (dir) => path.join(__dirname, dir);
const mockServer = () => isDev ? require("./mock/mockServer") : '';

module.exports = {
    publicPath,
    assetsDir,
    outputDir,
    lintOnSave,
    transpileDependencies,
    devServer: {
        hot: true,
        port: devPort,
        open: true,
        noInfo: false,
        overlay: {
            warnings: true,
            errors: true,
        },
        after: mockServer(),
    },
    configureWebpack:(config) => {
        config.externals = {
            vue: "Vue",
            "ant-design-vue": "ANTDESIGN",
            "vue-router": "VueRouter",
            vuex: "Vuex",
            moment: "MOMENT",
            axios: "axios"
        };
        config.plugins = [...config.plugins, new LodashModuleReplacementPlugin()]
    },
    chainWebpack: (config) => {
        const cdn = {
            css: [
                'https://cdn.bootcdn.net/ajax/libs/ant-design-vue/2.0.0-beta.10/antd.min.css'
            ],
            js: [
                'https://cdn.bootcdn.net/ajax/libs/vue/3.0.0/vue.cjs.min.js',
                'https://cdn.bootcdn.net/ajax/libs/vuex/4.0.0-beta.4/vuex.cjs.min.js',
                'https://cdn.bootcdn.net/ajax/libs/vue-router/4.0.0-beta.10/vue-router.cjs.min.js',
                'https://cdn.bootcdn.net/ajax/libs/ant-design-vue/2.0.0-beta.10/antd-with-locales.min.js',
                'https://cdn.bootcdn.net/ajax/libs/ant-design-vue/2.0.0-beta.10/antd.min.js',
                'https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.0/moment.min.js',
                'https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.0/locale/zh-cn.js',
                'https://cdn.bootcdn.net/ajax/libs/axios/0.20.0/axios.min.js'
            ]
        }
        config.plugins.delete("preload");
        config.plugins.delete("prefetch");
        config.plugin("html").tap(args => {
            // html中添加cdn
            args[0].cdn = cdn;
            return args;
        });
        config.resolve.alias
            .set("@", resolve("src"))
            .set("src", resolve("src"))
            .set("lodash", 'lodash-es')
        config.when(!isDev, (config) => {
            config.performance.set("hints", false);
            config.devtool("none");
            config.optimization.splitChunks({
                chunks: "all",
                cacheGroups: {
                    libs: {
                        name: "chunk-libs",
                        test: /[\\/]node_modules[\\/]/,
                        priority: 10,
                        chunks: "initial",
                    },
                    elementUI: {
                        name: "chunk-ant",
                        priority: 20,
                        test: /[\\/]node_modules[\\/]_?ant-design-vue(.*)/,
                    },
                },
            });
            config
                .plugin('ignore')
                .use(new Webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn$/))
                .end()
            config
                .plugin("compression")
                .use(CompressionWebpackPlugin, [
                    {
                        algorithm: "gzip",
                        test: /\.(js|css)$/,
                        threshold: 10240,
                        minRatio: 0.8,
                        deleteOriginalAssets: false
                    },
                ])
                .end();
            config.module
                .rule("images")
                .use("image-webpack-loader")
                .loader("image-webpack-loader")
                .options({
                    bypassOnDebug: true,
                })
                .end();
        });
        if (build7z) {
            config.when(!isDev, (config) => {
                config
                    .plugin("fileManager")
                    .use(FileManagerPlugin, [
                        {
                            onEnd: {
                                delete: [`./${outputDir}/video`, `./${outputDir}/data`],
                                archive: [
                                    {
                                        source: `./${outputDir}`,
                                        destination: `./${outputDir}/${outputDir}_${date}.7z`,
                                    },
                                ],
                            },
                        },
                    ])
                    .end();
            });
        }
    },
    runtimeCompiler: true,
    productionSourceMap: false,
    css: {
        requireModuleExtension: true,
        sourceMap: true,
        loaderOptions: {
            scss: {
                //sass loader 9.0配置写法
                additionalData(content, loaderContext) {
                    const { resourcePath, rootContext } = loaderContext;
                    const relativePath = path.relative(rootContext, resourcePath);
                    if (
                        relativePath.replace(/\\/g, "/") !== "src/styles/variables.scss"
                    ) {
                        return '@import "~@/styles/variables.scss";' + content;
                    }
                    return content;
                },
            },
        },
    },
};
